package service

import (
	"anban/models"
	"anban/utils"
	"context"
	"github.com/astaxie/beego/orm"
	"net/url"
	"strings"
)

// 获取设备海报信息
func GetDevicePictureInfo(p map[string]interface{}) *models.DevicePicture {
	o := orm.NewOrm()
	devicePicture := &models.DevicePicture{}
	qs := o.QueryTable("DevicePicture")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	qs.One(devicePicture)
	return devicePicture
}

// 添加设备海报信息
func AddDevicePicture(input url.Values) (int64, error) {
	o := orm.NewOrm()
	devicePicture := &models.DevicePicture{}
	device := &models.Device{}
	if _, ok := input["device_id"]; ok {
		device.Id = utils.Atoi64(input["device_id"][0])
		o.Read(device)
	}
	devicePicture.Device = device
	if _, ok := input["title"]; ok {
		devicePicture.Title = input["title"][0]
	}
	if _, ok := input["url"]; ok {
		devicePicture.Url = input["url"][0]
	}
	return o.Insert(devicePicture)
}

// 修改设备海报信息
func EditDevicePicture(input url.Values) (int64, error) {
	o := orm.NewOrm()
	p := orm.Params{}
	for k, v := range input {
		if k == "id" || k == "_xsrf" {
			continue
		}
		p[k] = v[0]
	}
	return o.QueryTable("DevicePicture").Filter("id", input["id"][0]).Update(p)
}

// 获取设备海报列表
func GetDevicePictureList(p map[string]interface{}) (int64, []*models.DevicePicture) {
	var devicePictureList []*models.DevicePicture
	o := orm.NewOrm()
	qs := o.QueryTable("DevicePicture")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["deviceId"]; ok {
		qs = qs.Filter("device_id", p["deviceId"])
	}
	if _, ok := p["ids"]; ok {
		qs = qs.Filter("id__in", strings.Split(p["ids"].(string), ","))
	}
	totalCount, _ := qs.Count()
	curPage, ok := p["curPage"]
	perCount, _ := p["perCount"]
	if ok {
		start := perCount.(int) * (curPage.(int) - 1)
		qs = qs.Limit(perCount, start)
	}
	qs.All(&devicePictureList)
	return totalCount, devicePictureList
}

func DelDevicePicture(p map[string]interface{}) (int64, error) {
	if len(p) < 1 {
		return -1, nil
	}
	o := orm.NewOrm()
	qs := o.QueryTable("DevicePicture")
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	if _, ok := p["deviceId"]; ok {
		qs = qs.Filter("device_id", p["deviceId"])
	}
	if _, ok := p["ids"]; ok {
		qs = qs.Filter("id__in", strings.Split(p["ids"].(string), ","))
	}
	return qs.Delete()
}

// 删除存储在腾讯云的图片对象
func DelPictureObj(ids string) {
	storageObj := utils.GetStorageObj()

	p := map[string]interface{}{}
	p["ids"] = ids
	_, devicePictureList := GetDevicePictureList(p)

	var objKey string
	for _, devicePicture := range devicePictureList {
		u, _ := url.Parse(devicePicture.Url)
		objKey = strings.Trim(u.Path, "/")
		storageObj.Object.Delete(context.Background(), objKey)
	}
}
